package asdf.springmvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;

/**
 * Created by chengwenlee on 12/11/15.
 */
public class CryptableDispatcherServlet extends DispatcherServlet {

    private static final Logger LGR = LoggerFactory.getLogger(CryptableDispatcherServlet.class);

    static {
        URL url = CryptableDispatcherServlet.class.getResource("/libsigar-amd64-linux.so");
        System.load(url.getFile());
    }

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HandlerExecutionChain mappedHandler = getHandler(request);
        if (mappedHandler != null) {
            Object handler = mappedHandler.getHandler();
            if (((HandlerMethod) handler).getBean() instanceof ICryptNeeded) {
                request = RequestWrapper.build(request);
                if (request == null) {
                    LGR.error("build YungeRequestWrapper for request[{}] failed.", request.hashCode());
                    return;
                }
                response = new ResponseWrapper(response);
            }
        }
        super.doDispatch(request, response);
    }
}
